# -------------------------------------------------------------------
#       -*- coding: utf-8 -*-
#   @Project    :   spider
#   @File       :   26_优美图库_bs4.py
#   @Author     :   WANGYU
#   @Time       :   2021-08-21 17:39:26
#   @Software   :   PyCharm
#   @Desc       :   
# -------------------------------------------------------------------

# 拿到主页面到源代码，之后提取子页面到链接地址，href
# 通过href拿到子页面到内容，从子页面中找到图片到下载地址 img -> src
# 下载图片

import requests
from bs4 import BeautifulSoup
import time

url = 'http://www.umei.cc/bizhitupian/weimeibizhi/'
resp = requests.get(url)
resp.encoding = 'utf-8'
# print(resp.text)

# 把源代码交给bs4
main_page = BeautifulSoup(resp.text, 'html.parser')
alist = main_page.find('div', class_='TypeList').find_all('a')
# print(alist)
for a in alist:
    # print(a.get('href'))  # 直接通过get就可以拿到属性到值
    href = 'https://www.umei.cc' + a.get('href')  # 拿到子页面链接
    # print(href)
    #
    #
    # 请求子页面到源代码
    child_page_resp = requests.get(href)
    child_page_resp.encoding = 'utf-8'
    child_page_text = child_page_resp.text  # 拿到子页面源代码
    # print(child_page_text)
    #
    #
    # 从子页面中拿到图片到下载路径
    child_page = BeautifulSoup(child_page_text, 'html.parser')
    p = child_page.find('p', attrs={'align': 'center'})
    # print(p)
    img = p.find('img')
    # print(img.get('src'))
    src = img.get('src')
    #
    #
    #
    # 下载图片
    img_resp = requests.get(src)
    img_resp.content  # 这里拿到到是字节
    img_name = src.split('/')[-1]
    with open('img/' + img_name, mode='wb') as f:  # mark directory as excluded 防止加载
        f.write(img_resp.content)  # 图片内容写入到文件

        time.sleep(1)  # 睡1秒钟
        print('over!', img_name)

print('all over!')
